<template>
  <div :id="mapId" style="height: 100%; width: 100%; background: black"></div>
</template>

<script>
import { Feature, Map, View } from 'ol'
import { Vector as VectorSource, XYZ } from 'ol/source'
import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer'
import { defaults as defaultInteractions } from 'ol/interaction'
import * as olControl from 'ol/control'
import { LineString, Point, Polygon } from 'ol/geom'
import { WKT } from 'ol/format'
import { Fill, Stroke, Style, Icon, Text } from 'ol/style'
import Overlay from 'ol/Overlay'
import { mapGetters } from 'vuex'

export default {
  data() {
    return {
      mapId: 'map',
      olMap: null,
      olView: null,
      layerMap: {},
      YXLayer: null,
      SLLayer: null,
      YXBZLayer: null,
      SLBZLayer: null,
      locationInterval: null,
      positionImg: require('../assets/position.png'),
      onlineJKImg: require('../assets/ic_jk_online.png'),
      offlineJKImg: require('../assets/ic_jk_offline.png'),
      selectedJKImg: require('../assets/ic_jk_selected.png'),
      location: null
    }
  },
  computed: {
    ...mapGetters(['getNativeApi'])
  },
  created() {
    this.mapId = 'map' + this.$getGuid()
  },
  mounted() {
    this.initMap()
    this.addBaseLayer()
    this.addLocation()
    this.locationInterval = setInterval(() => {
      this.setLocation()
    }, 500)
    this.$emit('mapInited', this.olMap, this.olView)
  },
  methods: {
    initMap() {
      this.olView = new View({
        projection: 'EPSG:4326',
        // extent: [118.170346825147, 35.7092226318004, 120.010406168387, 37.3274342089649],
        zoom: 14,
        center: [116.397428, 39.90923],
        smoothResolutionConstraint: false,
        constrainResolution: false
      })
      this.olMap = new Map({
        target: this.mapId,
        view: this.olView,
        logo: 'false',
        controls: olControl.defaults({
          zoom: false,
          attribution: false,
          rotate: false
        }),
        interactions: defaultInteractions({
          pinchRotate: false // 移动端禁止地图旋转
        })
      })
    },
    addBaseLayer() {
      //影像底图
      this.YXLayer = new TileLayer({
        source: new XYZ({
          url: `http://t{0-6}.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=05e70131897a88c01671c438bd1317f0`
        })
      })
      //影像注记
      this.YXBZLayer = new TileLayer({
        source: new XYZ({
          url: `http://t{0-6}.tianditu.gov.cn/cia_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=05e70131897a88c01671c438bd1317f0`
        }),
        zIndex: 1
      })
      //矢量底图
      this.SLLayer = new TileLayer({
        source: new XYZ({
          url: `http://t{0-6}.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=05e70131897a88c01671c438bd1317f0`
        })
      })
      //矢量注记
      this.SLBZLayer = new TileLayer({
        source: new XYZ({
          url: `http://t{0-6}.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=05e70131897a88c01671c438bd1317f0`
        }),
        zIndex: 1
      })
      //行政区图层
      this.xzqShapeLayer = new VectorLayer({
        source: new VectorSource(),
        properties: {
          target: 'XZQSHAPE'
        },
        minZoom: 4
      })
      //矿产图层
      this.ksShapeLayer = new VectorLayer({
        source: new VectorSource(),
        properties: {
          target: 'KSSHAPE'
        },
        minZoom: 4
      })
      //监控图层
      this.jkShapeLayer = new VectorLayer({
        source: new VectorSource(),
        properties: {
          target: 'JKSHAPE'
        },
        minZoom: 4
      })
      this.locationLayer = new VectorLayer({
        source: new VectorSource(),
        properties: {
          target: 'LOCATION'
        },
        minZoom: 4
      })

      this.olMap.addLayer(this.YXLayer)
      this.olMap.addLayer(this.SLLayer)
      this.olMap.addLayer(this.YXBZLayer)
      this.olMap.addLayer(this.SLBZLayer)
      this.SLLayer.setVisible(false)
      this.SLBZLayer.setVisible(false)

      this.olMap.addLayer(this.xzqShapeLayer)
      this.olMap.addLayer(this.ksShapeLayer)
      this.olMap.addLayer(this.jkShapeLayer)
      this.olMap.addLayer(this.locationLayer)
      this.layerMap['XZQSHAPE'] = this.xzqShapeLayer
      this.layerMap['KSSHAPE'] = this.ksShapeLayer
      this.layerMap['JKSHAPE'] = this.jkShapeLayer
    },
    changeBaseLayer(type) {
      switch (type) {
        case 'YX':
          this.YXLayer.setVisible(true)
          this.YXBZLayer.setVisible(true)
          this.SLLayer.setVisible(false)
          this.SLBZLayer.setVisible(false)
          break
        case 'SL':
          this.YXLayer.setVisible(false)
          this.YXBZLayer.setVisible(false)
          this.SLLayer.setVisible(true)
          this.SLBZLayer.setVisible(true)
          break
      }
    },
    addLocation() {
      this.getNativeApi.getLocationInfo().then(res => {
        const result = JSON.parse(res.data)
        this.location = [result.Longitude, result.Latitude]
        let point = new Feature({
          geometry: new Point(this.location)
        })
        point.setStyle(
          new Style({
            image: new Icon({
              src: this.positionImg,
              scale: 0.55,
              rotation: (3.14 / 180) * result.Angle
            })
          })
        )
        point.setId('location-self')
        this.locationLayer.getSource().addFeature(point)
        this.olView.setZoom(16)
        this.olView.setCenter(this.location)
      })
    },
    setLocation() {
      this.getNativeApi.getLocationInfo().then(res => {
        const result = JSON.parse(res.data)
        this.location = [result.Longitude, result.Latitude]
        const feature = this.locationLayer.getSource().getFeatureById('location-self')
        feature.setGeometry(new Point(this.location))
        feature.setStyle(
          new Style({
            image: new Icon({
              src: this.positionImg,
              scale: 0.55,
              rotation: (3.14 / 180) * result.Angle
            })
          })
        )
      })
    },
    positionSelf() {
      this.olView.animate({ zoom: 16, center: this.location, duration: 600 })
    },
    jurisdiction(minx, maxx, miny, maxy) {
      // 创建四至范围
      const extent = [minx, miny, maxx, maxy] // 最小经度、最小纬度、最大经度、最大纬度
      // 定位到四至范围
      this.olView.fit(extent, { padding: [10, 10, 10, 10] })
    },
    changeResolution(callback) {
      this.olView.on('change:resolution', callback)
    },
    addSingleClick(callback) {
      this.olMap.on('singleclick', callback)
    },
    getLayerMap() {
      return this.layerMap
    },
    getKSDefalutStyle(ksmc) {
      return new Style({
        fill: new Fill({
          color: 'rgba(19, 226, 132, 0.1)'
        }),
        stroke: new Stroke({
          color: '#13E284',
          width: 1
        }),
        text: new Text({
          font: 'normal 14px 黑体',
          // // 对其方式
          textAlign: 'center',
          // 基准线
          textBaseline: 'middle',
          // 文本填充样式
          fill: new Fill({
            color: '#13E284'
          }),
          padding: [5, 5, 5, 5],
          text: ksmc
        }),
        zIndex: 0
      })
    },
    getKSSelectedStyle(ksmc) {
      return new Style({
        fill: new Fill({
          color: 'rgba(255,198,0,0.1)'
        }),
        stroke: new Stroke({
          color: '#FFC600',
          width: 1
        }),
        text: new Text({
          font: 'normal 14px 黑体',
          // // 对其方式
          textAlign: 'center',
          // 基准线
          textBaseline: 'middle',
          // 文本填充样式
          fill: new Fill({
            color: '#FFC600'
          }),
          padding: [5, 5, 5, 5],
          text: ksmc
        }),
        zIndex: 1
      })
    },

    createOverlay(element, position, params = {}) {
      let overlay = new Overlay({
        element: element,
        ...params
      })
      overlay.setPosition(position)
      return overlay
    },
    createGeometryCollection(wktList) {
      const geometryCollectionWkt = `GEOMETRYCOLLECTION(${wktList.join()})`
      const format = new WKT()
      const feature = format.readFeature(geometryCollectionWkt)
      return feature
    },
    createJKFeature(point) {
      const feature = new Feature({
        geometry: new Point(point)
      })
      return feature
    },
    getJKOnlineStyle(jkmc) {
      return new Style({
        image: new Icon({
          src: this.onlineJKImg,
          scale: 0.55
        }),
        text: new Text({
          font: 'normal 14px 黑体',
          // // 对其方式
          textAlign: 'center',
          // 基准线
          textBaseline: 'middle',
          // 文本填充样式
          fill: new Fill({
            color: '#13E284'
          }),
          overflow: true,
          padding: [5, 5, 5, 5],
          text: jkmc,
          offsetY: -20
        }),
        zIndex: 0
      })
    },
    getJKOfflineStyle(jkmc) {
      return new Style({
        image: new Icon({
          src: this.offlineJKImg,
          scale: 0.55
        }),
        text: new Text({
          font: 'normal 14px 黑体',
          // // 对其方式
          textAlign: 'center',
          // 基准线
          textBaseline: 'middle',
          // 文本填充样式
          fill: new Fill({
            color: '#B1B1B1'
          }),
          overflow: true,
          padding: [5, 5, 5, 5],
          text: jkmc,
          offsetY: -20
        }),
        zIndex: 0
      })
    },
    getJKSelectedStyle(jkmc) {
      return new Style({
        image: new Icon({
          src: this.selectedJKImg,
          scale: 0.55
        }),
        text: new Text({
          font: 'normal 14px 黑体',
          // // 对其方式
          textAlign: 'center',
          // 基准线
          textBaseline: 'middle',
          // 文本填充样式
          fill: new Fill({
            color: '#FFC600'
          }),
          overflow: true,
          padding: [5, 5, 5, 5],
          text: jkmc,
          offsetY: -20
        }),
        zIndex: 1
      })
    },
    createXZQFeature(wkt) {
      const format = new WKT()
      const feature = format.readFeature(wkt)
      return feature
    },
    getXZQDefalutStyle() {
      return new Style({
        stroke: new Stroke({
          color: '#FF0000',
          width: 1
        }),
        zIndex: 0
      })
    },
    getXZQSelectStyle() {
      return new Style({
        stroke: new Stroke({
          color: '#FF0000',
          width: 2
        })
      })
    }
  },
  destroyed() {
    if (this.locationInterval) {
      clearInterval(this.locationInterval)
    }
    this.olMap = null
    this.olView = null
  }
}
</script>

<style lang="scss" scoped>
.preview-map {
  height: 100%;
  position: relative;
}
</style>
